<template>
  <div :class="$style.container">
    <h4>{{ name }}·涨姿势深度解读</h4>
    <p :class="$style.tip">如果你对剧情/台词/人物角色或任何角度有你的思考和观点，请与大家分享</p>
    <section v-show="!isDisplayEditor">
      <div 
        :class="$style.comment" 
        @click.stop="">
        <span>我来评分: <el-rate 
          v-model="star" 
          :class="$style.rate"
          :max="10"/></span>
        <el-input 
          v-model="title" 
          placeholder="请输入标题"
          @focus="focus"
        />
        <div v-show="isShow">
          <div 
            id="editor" 
            :class="$style.editor"/>
          <el-button 
            :class="$style.btn" 
            @click.stop="handleCommentClick">我来解读</el-button>
        </div>
      </div>
      <div :class="$style.input"/>
    </section>
  </div>
</template>

<script>
import { domain } from '../../util/config'
import http from '../../APIService/http'
export default {
  props: {
    name: {
      type: String,
      default: ''
    },
    doubanId: {
      type: String,
      default: ''
    },
    isDisplayEditor: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      star: 0,
      title: '', // 评论输入的标题
      editor: '',
      text: '', //富文本框的内容
      isShow: false
    }
  },
  mounted() {
    let that = this
    document.body.addEventListener('click', this.hide, false)
    this.initEditor()
  },
  beforeDestory() {
    document.body.removeEventListener('click', this.hide, false)
  },
  methods: {
    // input 获取焦点
    focus() {
      this.isShow = true
    },
    // 隐藏评论区域的富文本框
    hide() {
      this.isShow = false
    },
    //初始化富文本框
    initEditor() {
      let that = this
      this.editor = new E('#editor')
      this.editor.customConfig.menus = ['bold', 'image']
      this.editor.customConfig.onchange = html => {
        // html 即变化之后的内容
        this.text = html
      }
      this.editor.customConfig.uploadImgServer = `${domain}uploadFile`
      this.editor.customConfig.uploadImgMaxLength = 3
      this.editor.customConfig.uploadFileName = 'files'
      this.editor.customConfig.uploadImgHooks = {
        success: function(xhr, editor, result) {
          console.log('success:', result)
          // 图片上传并返回结果，图片插入成功之后触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
        },
        fail: function(xhr, editor, result) {
          // 图片上传并返回结果，但图片插入错误时触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
          console.log('fail:', result)
        },
        error: function(xhr, editor) {
          console.log('error:', xhr)
          // 图片上传出错时触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
        },
        customInsert: function(insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
          if (result.code === 0) {
            result.data.forEach(item => {
              let url = `${domain}downLoadFile?fileId=${item._id}`
              insertImg(url)
            })
          } else {
            console.log('response error:', result)
          }

          // result 必须是一个 JSON 格式字符串！！！否则报错
        }
      }
      this.editor.customConfig.customAlert = info => {
        // info 是需要提示的内容
        this.$message({
          type: 'error',
          message: `上传发生了错误:${info}`
        })
      }
      this.editor.customConfig.zIndex = 10
      this.editor.create()
    },
    // 提交评论
    async handleCommentClick() {
      try {
        if (!this.$store.state.user.user.userId) {
          this.$store.commit('SET_SHOW', true)
          return false
        }
        if (!this.star) {
          this.$message({
            type: 'error',
            message: '请先评分'
          })
          return false
        }
        if (!this.title) {
          this.$message({
            type: 'error',
            message: '请先输入标题'
          })
          return false
        }
        if (!this.text) {
          this.$message({
            type: 'error',
            message: '请先输入评论内容'
          })
          return false
        }
        let params = {
          star: this.star,
          title: this.title,
          content: this.text,
          id: this.doubanId,
          name: this.name
        }
        let res = await http.post(`/comment/add`, params)
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '评论成功'
          })
          this.$emit('commentSuccess')
        }
      } catch (err) {
        console.log('submit comment fail:', err)
      }
    }
  }
}
</script>

<style lang='scss' module>
.container {
  margin-top: 50px;
  h4 {
    font-size: 24px;
    line-height: 36px;
    color: #444;
  }
  .tip {
    font-size: 12px;
    line-height: 28px;
    color: #999;
    padding-bottom: 10px;
  }
  .comment {
    padding: 20px;
    background: #f5f5f4;
    &:after {
      display: block;
      content: ' ';
      overflow: hidden;
      clear: both;
    }
    .rate {
      margin-bottom: 20px;
      display: inline-block;
      vertical-align: 2px;
    }
    .editor {
      margin-top: 20px;
    }
    .btn {
      float: right;
      margin-top: 15px;
      width: 120px;
      height: 42px;
      font-size: 16px;
      background: #e36049;
      color: #fff;
      text-align: center;
      &:hover {
        border: 1px solid #e36049;
      }
    }
  }
}
</style>
